﻿using System;
using System.Linq;
using System.Xml.Linq;
using BSDS.Core.Model.Services.Jobs;
using BSDS.Core.Model.Services.Jobs.Core;

namespace BSDS.Core.Data.Remote.Download
{
    public class DownloadResponseParser : ResponseParserBase
    {
         public DownloadJob ParseCreateUploadJobResponse(string response)
         {
             const string xmlns = "http://schemas.microsoft.com/search/local/ws/rest/v1";

             var document = XDocument.Parse(response);

             return document.Descendants(XName.Get("DataflowJob", xmlns))
                            .Select(job => new DownloadJob
                            {
                                Id = job.Element(XName.Get("Id", xmlns)).Value.Trim(),
                                Link = job.Element(XName.Get("Link", xmlns)).Value.Trim(),
                                SubmissionDate = DateTime.Parse(job.Element(XName.Get("CreatedDate", xmlns)).Value.Trim())
                            }).First();
         }

        public JobState ParseGetStatusResponse(string jobId, string response)
        {
            const string xmlns = "http://schemas.microsoft.com/search/local/ws/rest/v1";

            var document = XDocument.Parse(response);

            var statusValue = document.Descendants(XName.Get("DataflowJob", xmlns))
                           .Select(l => l.Element(XName.Get("Status", xmlns)))
                           .First().Value;
            var successLink = GetLink(document, xmlns, "output");
            var failureLink = GetLink(document, xmlns, "failed");
            var completedDate = GetCompletionDate(document, xmlns);

            var status = (JobStatus)Enum.Parse(typeof(JobStatus), statusValue);

            var complitionStatus = JobComplitionStatus.Success;
            if(successLink == null || !successLink.EndsWith("succeeded"))
            {
                complitionStatus = JobComplitionStatus.Failure;
            }
            var result = new JobResult(complitionStatus, successLink, failureLink);

            return new JobState(jobId, status, result, 
                status == JobStatus.Aborted ? response : string.Empty, completedDate);
        }
    }
}